/*
 * Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.activity;

import org.json.JSONException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.JamendoApplication;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.R;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.adapter.RadioAdapter;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.api.JamendoGet2Api;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.api.Playlist;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.api.Radio;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.api.WSError;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.api.impl.JamendoGet2ApiImpl;
import com.mp3.dwonloader.ringtonemaker.musicradio.version.zl.db.DatabaseImpl;
import com.tools.recommend.NetworkHelper;

/**
 * Radio navigation activity
 * 
 * @author Lukasz Wisniewski
 */
public class RadioActivity extends Activity {

	/**
	 * statically (don't blame me) inserted recommended radios
	 */
	private static int[] recommended_ids = { 9, // rock
			4, // dance
			5, // hiphop
			6, // jazz
			7, // lounge
			8, // pop
			283 // metal
	};

	/**
	 * Recommended radios
	 */
	private Radio[] mRecommendedRadios;

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param c
	 *            context from which Activity should be started
	 */
	public static void launch(Context c) {
		final Intent intent = new Intent(c, RadioActivity.class);
		c.startActivity(intent);
	}

	private ListView mRadioListView;
	private RadioAdapter mRadioAdapter;
	private Button mButton;
	private EditText mEditText;
	private Spinner mSpinner;
	private ViewFlipper mViewFlipper;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search);

		mRadioListView = (ListView) findViewById(R.id.SearchListView);
		mRadioAdapter = new RadioAdapter(this);
		mRadioListView.setAdapter(mRadioAdapter);
		mRadioListView.setOnItemClickListener(mRadioListListener);
		mButton = (Button) findViewById(R.id.SearchButton);
		mButton.setText(R.string.radio);
		mButton.setOnClickListener(mButtonClickListener);
		mEditText = (EditText) findViewById(R.id.SearchEditText);
		mViewFlipper = (ViewFlipper) findViewById(R.id.SearchViewFlipper);

		mSpinner = (Spinner) findViewById(R.id.SearchSpinner);
		final ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.radio_modes, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinner.setAdapter(adapter);
		mEditText.setHint(R.string.radio_hint);

		loadRecommendedRadios();

		mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				switch (position) {
				case 0:
					// recent
					mRadioAdapter.setList(new DatabaseImpl(RadioActivity.this)
							.getRecentRadios(20));
					break;
				case 1:
					// recommended
					mRadioAdapter.setList(mRecommendedRadios);
					break;

				default:
					break;
				}

				setupListView();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}

		});

		// TODO (maybe) if recent.count > 0 set to recent
		mSpinner.setSelection(1);
		
		final LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
		final AdView adView = new AdView(this, AdSize.BANNER, "a14e3cab66eea7a");
		layout.addView(adView);
		adView.loadAd(new AdRequest());
	}

	/**
	 * Open radio by id or idstr
	 */
	private final OnClickListener mButtonClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			if (mEditText.getText().toString().length() == 0)
				return;

			int id = 0;
			String idstr = null;
			try {
				id = Integer.parseInt(mEditText.getText().toString()); // search
																		// by id
			} catch (final NumberFormatException e) {
				idstr = mEditText.getText().toString(); // search by name
			}

			Radio[] radio = null;
			try {
				final JamendoGet2Api service = new JamendoGet2ApiImpl();
				if (idstr == null && id > 0) {
					final int[] ids = { id };
					radio = service.getRadiosByIds(ids);
				} else if (idstr != null) {
					radio = service.getRadiosByIdstr(idstr);
				}
				mRadioAdapter.setList(radio);

				setupListView();

			} catch (final JSONException e) {
				e.printStackTrace();
			} catch (final WSError e) {
				// connection problem or sth/ finish
				Toast.makeText(RadioActivity.this, e.getMessage(),
						Toast.LENGTH_LONG).show();
				finish();
			}

		}

	};

	/**
	 * Displays no result message or results on ListView
	 */
	private void setupListView() {
		if (mRadioAdapter.getCount() > 0) {
			mViewFlipper.setDisplayedChild(0); // display results
		} else {
			mViewFlipper.setDisplayedChild(1); // display no results message
		}
	}

	private AsyncTask<Void, Void, Playlist> mAsyncTask;
	/**
	 * Launch radio
	 */
	private final OnItemClickListener mRadioListListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			final Radio radio = (Radio) mRadioAdapter.getItem(position);

			// Radio radio = (Radio) mRadioAdapter.getItem(position);
			// radio.setId(recommended_ids[position]);

			mAsyncTask = new AsyncTask<Void, Void, Playlist>() {
				private ProgressDialog mDialog;
				Playlist playlist = null;

				@Override
				protected void onPreExecute() {
					mDialog = new ProgressDialog(RadioActivity.this);
					mDialog.setMessage("Please wait while loading...");
					mDialog.setCancelable(true);
					mDialog.setCancelMessage(mHandler.obtainMessage(MSG_CANCEL));
					mDialog.show();
				}

				@Override
				protected Playlist doInBackground(Void... params) {
					if (NetworkHelper.isNetworkAvailable(RadioActivity.this)) {
						try {
							playlist = new JamendoGet2ApiImpl()
									.getRadioPlaylist(radio, 20,
											JamendoApplication.getInstance()
													.getStreamEncoding());

						} catch (final JSONException e) {
							e.printStackTrace();
						} catch (final WSError e) {
							// connection problem or sth/ finish
							Toast.makeText(RadioActivity.this,
									"Failed to get data from server.",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(RadioActivity.this,
								"Please check your network.",
								Toast.LENGTH_SHORT).show();
						return null;
					}
					return playlist;
				}

				@Override
				protected void onPostExecute(Playlist result) {
					if (playlist != null) {
						PlayerActivity.launch(RadioActivity.this, playlist);
					} else {

					}
					if (mDialog.isShowing()) {
						try {
							mDialog.dismiss();
						} catch (final Exception e) {
						}
					}
				};

			};
			mAsyncTask.execute();

			// try {
			// Playlist playlist = new JamendoGet2ApiImpl().getRadioPlaylist(
			// radio, 20, JamendoApplication.getInstance()
			// .getStreamEncoding());
			// new DatabaseImpl(RadioActivity.this).addRadioToRecent(radio);
			// PlayerActivity.launch(RadioActivity.this, playlist);
			// } catch (JSONException e) {
			// e.printStackTrace();
			// } catch (WSError e) {
			// // connection problem or sth/ finish
			// Toast.makeText(RadioActivity.this, e.getMessage(),
			// Toast.LENGTH_LONG).show();
			// finish();
			// }
		}

	};
	private static final int MSG_CANCEL = 123;
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_CANCEL:
				if (mAsyncTask.getStatus() == Status.RUNNING) {
					mAsyncTask.cancel(true);
				}
				break;
			}
		}

	};

	private void loadRecommendedRadios() {
		try {
			mRecommendedRadios = new JamendoGet2ApiImpl()
					.getRadiosByIds(recommended_ids);
		} catch (final JSONException e) {
			e.printStackTrace();
		} catch (final WSError e) {
			// connection problem or sth/ finish
			Toast.makeText(RadioActivity.this, e.getMessage(),
					Toast.LENGTH_LONG).show();
			finish();
		}
	}
}
